using UnityEngine;

/// <summary>
/// 【保持16:9画面比例 + 黑边适配】
/// 适用场景：
/// - 游戏需要固定在 16:9 画面比例展示（防止 UI 拉伸）
/// - 自动调整全屏窗口分辨率以适配目标比例
/// 使用方法：
/// - 将本脚本挂载到主相机（Camera）上
/// </summary>
[RequireComponent(typeof(Camera))]
public class FixedAspectRatio : MonoBehaviour
{
    [Header("目标画面比例")]
    [Tooltip("例如16:9为 1.7777...")]
    [SerializeField] private float targetAspect = 16f / 9f;

    private void Start()
    {
        AdjustScreenResolution();
    }

    /// <summary>
    /// 调整屏幕分辨率以适配目标比例
    /// </summary>
    private void AdjustScreenResolution()
    {
        int screenWidth = Screen.currentResolution.width;
        int screenHeight = Screen.currentResolution.height;

        float currentAspect = (float)screenWidth / screenHeight;

        if (Mathf.Approximately(currentAspect, targetAspect))
        {
            // 比例已接近，不调整
            return;
        }

        if (currentAspect > targetAspect)
        {
            // 当前屏幕更宽，缩放宽度
            int newWidth = Mathf.RoundToInt(screenHeight * targetAspect);
            Screen.SetResolution(newWidth, screenHeight, FullScreenMode.FullScreenWindow);
        }
        else
        {
            // 当前屏幕更高，缩放高度
            int newHeight = Mathf.RoundToInt(screenWidth / targetAspect);
            Screen.SetResolution(screenWidth, newHeight, FullScreenMode.FullScreenWindow);
        }
    }
}
